<template>
  <!-- 包含所有内容的主容器 -->
  <div class="home" style="padding: 10px">

    <!-- 搜索表单 -->
    <div style="margin: 10px 0;">
      <el-form inline="true" size="small">
        <!-- 图书编号输入框 -->
        <el-form-item label="图书编号">
          <el-input v-model="search1" placeholder="请输入图书编号" clearable>
            <template #prefix><el-icon class="el-input__icon"><search /></el-icon></template>
          </el-input>
        </el-form-item>
        <!-- 图书名称输入框 -->
        <el-form-item label="图书名称">
          <el-input v-model="search2" placeholder="请输入图书名称" clearable>
            <template #prefix><el-icon class="el-input__icon"><search /></el-icon></template>
          </el-input>
        </el-form-item>
        <!-- 作者输入框 -->
        <el-form-item label="作者">
          <el-input v-model="search3" placeholder="请输入作者" clearable>
            <template #prefix><el-icon class="el-input__icon"><search /></el-icon></template>
          </el-input>
        </el-form-item>
        <!-- 查询按钮 -->
        <el-form-item>
          <el-button type="primary" style="margin-left: 1%" @click="load" size="mini">
            <svg-icon iconClass="search" />查询
          </el-button>
        </el-form-item>
        <!-- 重置按钮 -->
        <el-form-item>
          <el-button size="mini" type="danger" @click="clear">重置</el-button>
        </el-form-item>
        <!-- 逾期通知按钮 -->
        <el-form-item style="float: right" v-if="numOfOutDataBook!=0">
          <el-popconfirm
            confirm-button-text="查看"
            cancel-button-text="取消"
            :icon="InfoFilled"
            icon-color="red"
            title="您有图书已逾期，请尽快归还"
            @confirm="toLook"
          >
            <template #reference>
              <el-button type="warning">逾期通知</el-button>
            </template>
          </el-popconfirm>
        </el-form-item>
      </el-form>
    </div>

    <!-- 按钮区 -->
    <div style="margin: 10px 0;">
      <!-- 上架按钮，仅管理员可见 -->
      <el-button type="primary" @click="add" v-if="user.role == 1">上架</el-button>
      <!-- 批量删除按钮，仅管理员可见 -->
      <el-popconfirm title="确认删除?" @confirm="deleteBatch" v-if="user.role == 1">
        <template #reference>
          <el-button type="danger" size="mini">批量删除</el-button>
        </template>
      </el-popconfirm>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" stripe border="true" @selection-change="handleSelectionChange">
      <!-- 多选框列，仅管理员可见 -->
      <el-table-column v-if="user.role == 1" type="selection" width="55"></el-table-column>
      <!-- 图书编号列 -->
      <el-table-column prop="isbn" label="图书编号" sortable />
      <!-- 图书名称列 -->
      <el-table-column prop="name" label="图书名称" />
      <!-- 价格列 -->
      <el-table-column prop="price" label="价格" sortable />
      <!-- 作者列 -->
      <el-table-column prop="author" label="作者" />
      <!-- 出版社列 -->
      <el-table-column prop="publisher" label="出版社" />
      <!-- 出版时间列 -->
      <el-table-column prop="createTime" label="出版时间" sortable />
      <!-- 状态列 -->
      <el-table-column prop="status" label="状态">
        <template v-slot="scope">
          <el-tag v-if="scope.row.status == 0" type="warning">已借阅</el-tag>
          <el-tag v-else type="success">未借阅</el-tag>
        </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column fixed="right" label="操作">
        <template v-slot="scope">
          <!-- 修改按钮，仅管理员可见 -->
          <el-button size="mini" @click="handleEdit(scope.row)" v-if="user.role == 1">修改</el-button>
          <!-- 删除按钮，仅管理员可见 -->
          <el-popconfirm title="确认删除?" @confirm="handleDelete(scope.row.id)" v-if="user.role == 1">
            <template #reference>
              <el-button type="danger" size="mini">删除</el-button>
            </template>
          </el-popconfirm>
          <!-- 借阅按钮，仅普通用户可见 -->
          <el-button size="mini" @click="handlelend(scope.row.id,scope.row.isbn,scope.row.name,scope.row.borrownum)" v-if="user.role == 2" :disabled="scope.row.status == 0">借阅</el-button>
          <!-- 还书按钮，仅普通用户可见 -->
          <el-popconfirm title="确认还书?" @confirm="handlereturn(scope.row.id,scope.row.isbn,scope.row.borrownum)" v-if="user.role == 2" :disabled="scope.row.status == 1">
            <template #reference>
              <el-button type="danger" size="mini" :disabled="(this.bookIdArray.indexOf(scope.row.id)) == -1 || scope.row.status == 1">还书</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 逾期通知对话框 -->
    <el-dialog
      v-model="dialogVisible3"
      v-if="numOfOutDataBook!=0"
      title="逾期详情"
      width="50%"
      :before-close="handleClose"
    >
      <el-table :data="outDateBook" style="width: 100%">
        <el-table-column prop="isbn" label="图书编号" />
        <el-table-column prop="bookName" label="书名" />
        <el-table-column prop="lendtime" label="借阅日期" />
        <el-table-column prop="deadtime" label="截至日期" />
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="dialogVisible3 = false">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分页组件 -->
    <div style="margin: 10px 0">
      <el-pagination
        v-model:currentPage="currentPage"
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>

      <!-- 上架书籍对话框 -->
      <el-dialog v-model="dialogVisible" title="上架书籍" width="30%">
        <el-form :model="form" label-width="120px">
          <el-form-item label="图书编号">
            <el-input style="width: 80%" v-model="form.isbn"></el-input>
          </el-form-item>
          <el-form-item label="图书名称">
            <el-input style="width: 80%" v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="价格">
            <el-input style="width: 80%" v-model="form.price"></el-input>
          </el-form-item>
          <el-form-item label="作者">
            <el-input style="width: 80%" v-model="form.author"></el-input>
          </el-form-item>
          <el-form-item label="出版社">
            <el-input style="width: 80%" v-model="form.publisher"></el-input>
          </el-form-item>
          <el-form-item label="出版时间">
            <div>
              <el-date-picker value-format="YYYY-MM-DD" type="date" style="width: 80%" clearable v-model="form.createTime"></el-date-picker>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="save">确 定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 修改书籍信息对话框 -->
      <el-dialog v-model="dialogVisible2" title="修改书籍信息" width="30%">
        <el-form :model="form" label-width="120px">
          <el-form-item label="图书编号">
            <el-input style="width: 80%" v-model="form.isbn"></el-input>
          </el-form-item>
          <el-form-item label="图书名称">
            <el-input style="width: 80%" v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="价格">
            <el-input style="width: 80%" v-model="form.price"></el-input>
          </el-form-item>
          <el-form-item label="作者">
            <el-input style="width: 80%" v-model="form.author"></el-input>
          </el-form-item>
          <el-form-item label="出版社">
            <el-input style="width: 80%" v-model="form.publisher"></el-input>
          </el-form-item>
          <el-form-item label="出版时间">
            <div>
              <el-date-picker value-format="YYYY-MM-DD" type="date" style="width: 80%" clearable v-model="form.createTime"></el-date-picker>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="save">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>


<script>
// 导入request模块，用于处理HTTP请求
import request from "../utils/request";
// 导入Element Plus的消息组件，用于显示提示信息
import { ElMessage } from "element-plus";
// 导入moment库，用于处理日期和时间
import moment from "moment";

// 默认导出Vue组件
export default {
  // 组件创建时的钩子函数
  created() {
    // 从sessionStorage获取用户信息，若不存在则使用空对象
    let userStr = sessionStorage.getItem("user") || "{}";
    // 将获取的用户信息解析为JSON对象并赋值给this.user
    this.user = JSON.parse(userStr);
    // 加载数据
    this.load();
  },
  name: "Book", // 组件名称
  methods: {
    // 处理表格选择项变化
    handleSelectionChange(val) {
      // 获取选择项的ID数组
      this.ids = val.map(v => v.id);
    },
    // 批量删除
    deleteBatch() {
      // 若未选择任何数据，显示警告信息并返回
      if (!this.ids.length) {
        ElMessage.warning("请选择数据！");
        return;
      }
      // 发送批量删除请求
      request.post("/book/deleteBatch", this.ids).then(res => {
        // 若删除成功，显示成功信息并重新加载数据
        if (res.code === "0") {
          ElMessage.success("批量删除成功");
          this.load();
        } else {
          // 若删除失败，显示错误信息
          ElMessage.error(res.msg);
        }
      });
    },
    // 加载数据
    load() {
      // 初始化逾期图书数量和数据
      this.numOfOutDataBook = 0;
      this.outDateBook = [];
      // 发送获取图书数据的请求
      request.get("/book", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          search1: this.search1,
          search2: this.search2,
          search3: this.search3,
        }
      }).then(res => {
        // 将获取的图书数据和总数赋值给相应的变量
        this.tableData = res.data.records;
        this.total = res.data.total;
      });

      console.log("this.user.role=", this.user.role);
      // 如果用户角色是2（普通用户），获取借阅记录
      if (this.user.role == 2) {
        console.log("this.user.role11=", this.user.role);
        request.get("/lendRecord", {
          params: {
            pageNum: "1",
            pageSize: this.total,
            search1: "",
            search2: this.user.id,
            search3: "0"
          }
        }).then(res => {
          this.bookData = res.data.records;
          this.number = this.bookData.length;
          var nowDate = new Date();
          console.log("this.number", res.data.records);
          // 遍历借阅记录，检查是否逾期
          for (let i = 0; i < this.number; i++) {
            this.bookIdArray[i] = this.bookData[i].bookId;
            console.log("第", i, "个isbn是", this.bookIdArray[i]);
            console.log("iii");
            let dDate = new Date(this.bookData[i].returnTime);
            // 若图书已逾期，将其加入逾期图书列表
            if (dDate < nowDate) {
              this.outDateBook[this.numOfOutDataBook] = {
                bookId: this.bookData[i].id,
                isbn: this.bookData[i].isbn,
                bookName: this.bookData[i].bookName,
                returnTime: this.bookData[i].returnTime,
                lendTime: this.bookData[i].lendTime
              };
              this.numOfOutDataBook = this.numOfOutDataBook + 1;
            }
          }
        });
      }
    },
    // 清空搜索条件并重新加载数据
    clear() {
      this.search1 = "";
      this.search2 = "";
      this.search3 = "";
      this.load();
    },
    // 删除单个图书
    handleDelete(id) {
      request.delete("book/" + id).then(res => {
        if (res.code == 0) {
          ElMessage.success("删除成功");
          this.load();
        } else {
          ElMessage.error(res.msg);
        }
      });
    },
    // 处理还书
    handlereturn(bookId, isbn, bn) {
      this.form.status = "1";
      this.form.id = bookId;

      request.put("/book", this.form).then(res => {
        if (res.code == 0) {
          ElMessage({
            message: '还书成功',
            type: 'success',
          });

          this.form3.bookId = bookId;
          console.log("bookId=", bookId);
          this.form3.isbn = isbn;
          this.form3.readerId = this.user.id;

          let endDate = moment(new Date()).format("yyyy-MM-DD HH:mm:ss");
          this.form3.returnTime = endDate;
          this.form3.status = "1";
          this.form3.borrownum = bn;

          request.put(`/lendRecord/${bookId}`, this.form3).then(res => {
            if (res.code == 0) {
              ElMessage.success("借阅记录更新成功");
              this.load();
            } else {
              ElMessage.error(res.msg);
            }
          }).catch(error => {
            console.error("Error updating lend record:", error);
            ElMessage.error("更新借阅记录时出错");
          });

        } else {
          ElMessage.error(res.msg);
        }
      }).catch(error => {
        console.error("Error returning book:", error);
        ElMessage.error("还书时出错");
      });
    },
    // 处理借书
    handlelend(bookId, isbn, name, bn) {
      if (this.number == 5) {
        ElMessage.warning("您不能再借阅更多的书籍了");
        return;
      }
      if (this.numOfOutDataBook != 0) {
        ElMessage.warning("在您归还逾期书籍前不能再借阅书籍");
        return;
      }

      this.form.status = "0";
      this.form.id = bookId;
      this.form.borrownum = bn + 1;

      request.put("/book", this.form).then(res => {
        console.log("bookId=", bookId)
        console.log("isbn=", isbn)
        console.log("name=", name)
        console.log("bn=", bn)
        if (res.code == 0) {
          ElMessage({
            message: '借阅成功',
            type: 'success',
          });

          this.form2.status = "0";
          this.form2.bookId = bookId;
          this.form2.isbn = isbn;
          this.form2.readerId = this.user.id;
          this.form2.borrownum = bn + 1;
          this.form2.lendTime = moment(new Date()).format("yyyy-MM-DD HH:mm:ss");
          this.form2.prolong = 1;

          request.post("/lendRecord", this.form2).then(res => {
            if (res.code == 0) {
              ElMessage.success("借阅记录创建成功");
              this.load();
            } else {
              ElMessage.error(res.msg);
            }
          }).catch(error => {
            console.error("Error creating lend record:", error);
            ElMessage.error("创建借阅记录时出错");
          });

        } else {
          ElMessage.error(res.msg);
        }
      }).catch(error => {
        console.error("Error borrowing book:", error);
        ElMessage.error("借阅书籍时出错");
      });
    },
    // 处理编辑操作
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogVisible2 = true;
    },
    // 处理分页大小变化
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.load();
    },
    // 处理当前页码变化
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.load();
    },
    // 查看逾期通知
    toLook() {
      this.dialogVisible3 = true;
    },
    // 显示添加书籍对话框
    add() {
      this.dialogVisible = true;
      this.form = {};  // 重置表单数据
    },
    // 保存书籍信息
    save() {
      if (this.form.id) {
        request.put("/book/update", this.form).then(res => {
          if (res.code == 0) {
            ElMessage.success("信息更新成功");
            this.dialogVisible = false;
            this.dialogVisible2 = false;
            this.load();
          } else {
            ElMessage.error(res.msg);
          }
        }).catch(error => {
          console.error("Error updating book:", error);
          ElMessage.error("更新书籍信息时出错");
        });
      } else {
        request.post("/book", this.form).then(res => {
          if (res.code == 0) {
            ElMessage.success("上架成功");
            this.dialogVisible = false;
            this.dialogVisible2 = false;
            this.load();
          } else {
            ElMessage.error(res.msg);
          }
        }).catch(error => {
          console.error("Error adding book:", error);
          ElMessage.error("上架书籍时出错");
        });
      }
    },
  },
  data() {
    return {
      form: {}, // 表单数据
      form2: {}, // 第二个表单数据
      form3: {}, // 第三个表单数据
      dialogVisible: false, // 上架书籍对话框是否可见
      dialogVisible2: false, // 修改书籍信息对话框是否可见
      search1: '', // 搜索条件1
      search2: '', // 搜索条件2
      search3: '', // 搜索条件3
      total: 10, // 总记录数
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示条数
      tableData: [], // 表格数据
      user: {}, // 用户信息
      number: 0, // 借阅图书数量
      bookData: [], // 借阅图书数据
      bookIdArray: [], // 借阅图书ID数组
      outDateBook: [], // 逾期图书数据
      numOfOutDataBook: 0, // 逾期图书数量
      dialogVisible3: true, // 逾期通知对话框是否可见
    }
  },
}
</script>
